package com.c2dm.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class sendMessage {
	String set(String registrationID,String authToken,String collapseKey,String message)
	{
		String rValue="";
		
		StringBuilder sb1 = new StringBuilder();
		addEncodedParameter(sb1, "registration_id", registrationID);
		addEncodedParameter(sb1, "collapse_key", collapseKey);
		addEncodedParameter(sb1, "data.payload", message);
		//addEncodedParameter(sb1, "data.payload2", "payload2 message data");
		//addEncodedParameter(sb1, "data.anotherPayload", "even more message data");
		String data = sb1.toString();

	   try
       {
		  StringBuffer sb = new StringBuffer(); 
          URL url=new URL("https://android.apis.google.com/c2dm/send");
          URLConnection conn = url.openConnection();
          conn.setDoOutput(true); 
          conn.setUseCaches(false);
          conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
          OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
          wr.write(data);
          wr.flush();
          
          BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String line;
           while ((line = rd.readLine()) != null) {
        	// Process line...
        	   sb.append(line); 
        	}
            rValue=sb.toString();
        	wr.close();
        	rd.close(); 
        	return rValue;

        }
        catch(MalformedURLException e)
        {
        }
        catch(IOException e)
        {
        }
        return rValue;
	}

	   public static void addEncodedParameter(StringBuilder sb, String name, String value) {
	    if (sb.length() > 0) {
	        sb.append("&");
	    }
	    try {
	        sb.append(URLEncoder.encode(name, "UTF-8"));
	        sb.append("=");
	        sb.append(URLEncoder.encode(value, "UTF-8"));
	    } catch (UnsupportedEncodingException e) {
	        // Exception handling
	    }
	}
	     
	   
}

